<template>
	<view class="content">
		<!-- 头部 -->
		<Header ref="Header" title="首页" class="top"></Header>
    <view class="other-item" >
      <view @click="checkedStatus()">
        <image  :src="isLogin&&isFacilitiesInfo?'../../static/gis_unbind@2x.png':'../../static/binds@2x.png'" style="width: 30rpx;height: 30rpx;margin-right: 22rpx;" mode="">
        </image>
        <text style="font-size: 32rpx">{{isLogin&&isFacilitiesInfo?"解绑一体机":"绑定一体机"}}</text>
      </view>

    </view>
		<!-- 列表 -->
		<view class="center">
      <view class="item-box"><view class="item_title">
        <image src="@/static/zhushou@2x.png"></image>
      </view></view>
      <view class="item-box">
        <view class="item-content"><image src="@/static/robot@2x.png"></image></view>
        <view class="item-content" v-if="!isLogin||!isFacilitiesInfo">未绑定一体机</view>
        <view class="item-content" v-if="isLogin&&isFacilitiesInfo">已绑定一体机</view>
        <view class="item-content"><span>机器人:</span><span>{{pc.device_id?pc.device_id:'---'}}</span></view>
      </view>
      <view class="item-box">
        <view class="top_vicoe" v-if="!isLogin||!isFacilitiesInfo">请先绑定一体机再进行语音</view>
        <view class="top_vicoe" v-if="isLogin&&isFacilitiesInfo&&longPress == '1'">点击请说话</view>
        <view class="top_vicoe" v-if="isLogin&&isFacilitiesInfo&&longPress == '2'">松开发送语音</view>
        <view class="vioce-item"  v-if="!isLogin||!isFacilitiesInfo">
          <image src="@/static/vioce@2x.png">
          </image>
        </view>
        <view v-if="isLogin&&isFacilitiesInfo" class="vioce-item"  @longpress="longpressBtn()"  @touchend="touchendBtn()">
          <image v-show="longPress == '1'" src="@/static/clickvioce@2x.png">
          </image>
          <image v-show="longPress == '2'" src="@/static/speakvioce@2x.png">
          </image>
        </view>
      </view>
		</view>
    <!-- 绑定一体机 -->
    <u-popup :show="show" :round="10" mode="center" @close="show = false">
      <view class="modal-box">
        <view class="close" @click="show = false">  <image src="@/static/close@2x.png"></image></view>
        <view class="modal-title">
          微信账号登录
        </view>
        <view class="info_self">
          <image class="self_img" src="@/static/infoimg@2x.png"></image>
          <view class="phone">
            {{userInfo.name || '花开那年春天'}}
          </view>
        </view>
        <view class="call-btn" @click="wechatLogin">
          微信授权登录
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
	import Header from '@/components/header.vue'
	export default {
		data() {
			return {
				title: 'Hello',
				keyword: '',
				show:false,
				isLogin:false,//判断用户是否微信登录
				moveup:true,
				voicePath: '', //音频路径
				longPress: '1', // 1显示 按住说话 2显示 说话中
				isFacilitiesInfo:false, //用户是否有绑定的设备信息
				pc:{},//用户的设备信息
			}
		},
		components: {
			Header
		},
		mounted() {

		},
		onLoad() {
		  this.checkedlogin()
		},
		methods: {
			checkedStatus(){
				if(!this.isLogin){
					this.show = true;
				}else if(this.isFacilitiesInfo){
					this.confirmUnbind()
				}else if(!this.isFacilitiesInfo){
					this.scan()
				}
			},
			checkedlogin(){
				if (!uni.getStorageSync('token')) {
					this.isLogin = false;
					this.show = true;
					return;
				}else{
					this.isLogin = true;
					this.getFacilitiesInfo()
				}
			},
			// 解绑设备
			confirmUnbind() {
				var that = this;
				uni.showModal({
					title: '是否解除绑定',
					content: '',
					success: function (res) {
						if (res.confirm) {
							that.UnbindFacilities()
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			UnbindFacilities(){
				let formData = {
					pc_id : this.pc.device_id,
					authorization:uni.getStorageSync('token')
				}
				uni.$u.http.post('/applet/remove_device',formData).then(res => {
					if(res.code){
						this.pc = {};
						this.isFacilitiesInfo = false;
					}else{
						this.isFacilitiesInfo = true;
            this.$u.toast(res.msg)
					}
				})
			},
			getFacilitiesInfo(){
				uni.$u.http.get(`/applet/info?authorization=${uni.getStorageSync('token')}`).then(res => {
					if(res.code){
						this.pc = res.pc;
						this.isFacilitiesInfo = true;
					}else{
						this.isFacilitiesInfo = false;
					}
				})
			},
		  //绑定设备调用微信扫码
			scan(){
				// 允许从相机和相册扫码
				var that = this;
				uni.scanCode({
				  success: function (res) {
					console.log('条码类型：' + res.scanType);
					console.log('条码内容：' + res.result);
					let formdata = {
						pc_id:res.result,
						authorization:uni.getStorageSync('token')
					}
					uni.$u.http.post('/applet/bind_device', formdata).then(res => {
						if(res.code){
							that.$u.toast('绑定成功');
							that.getFacilitiesInfo()
						}else{
							that.$u.toast(res.msg)
						}
					})
				  }
				});
			},
			// 微信登录
			wechatLogin() {
				uni.getUserProfile({
				  desc: '请求获取个人信息',
				  lang: 'zh_CN',
				  success: (userRes) => {
					if (userRes.errMsg === 'getUserProfile:ok') {
					  uni.login({
						provider: 'weixin',
						onlyAuthorize: true,
						success: (res) => {
						  let pramas = {
							code: res.code,
							nickName: userRes.userInfo.nickName,
							gender:userRes.userInfo.gender,
							city: userRes.userInfo.city,
							province:userRes.userInfo.province,
							avatarUrl: userRes.userInfo.avatarUrl,
							country:userRes.userInfo.country,
						  }
						  uni.$u.http.post('/user/login', pramas).then(bindRes => {
							if (bindRes.code) {
							  this.$u.toast('登录成功')
							  uni.setStorageSync('token', bindRes.data)
							  this.isLogin = true;
							  this.show = false;
							  this.getFacilitiesInfo();
							}else{
                this.$u.toast(bindRes.msg)
              }
						  })
						}
					  })
					} else {
					  this.$u.toast('授权失败')
					}

				  }
				})
			},
			longpressBtn(){
				this.longPress = '2';
				const options = {
				  sampleRate: 16000, // 采样率
				  numberOfChannels: 1, // 录音通道数
				  encodeBitRate: 96000, // 编码码率
				  format: 'PCM', // 音频格式，有效值 aac/mp3
				  frameSize: 10, // 指定帧大小，单位 KB
				}
				recorderManager.start(options);
				// 监听音频开始事件
				recorderManager.onStart((res) => {
				  console.log(res)
				})
			},
			touchendBtn(){
				this.longPress = '1';
				recorderManager.onStop((res) => {
				  this.voicePath = res.tempFilePath
				  this.uploadRecord(this.voicePath)
				})
				recorderManager.stop()
			},
			uploadRecord(tempFilePath) {
			    // tempFilePath为RecorderManager对象返回的录⾳⽂件临时地址
			    const uploadTask = uni.uploadFile({
					url: `https://kaniao.xiaochun1.com/api2/applet/upload_voice?pc_id=${this.pc.device_id}&authorization=${uni.getStorageSync('token')}`,
					filePath: tempFilePath, //录⾳结束后返回的临时路径
					name: 'picFile', // ⽂件对应的 key值对象名称
					header: {
					 'content-type': 'multipart/form-data',
					 'authorization': uni.getStorageSync('token')
					},
					success: (res) => {
            console.log('-----上传成功-----'+JSON.stringify(res),res)
            this.$u.toast(JSON.parse(res.data).msg);
					},
					fail: (res) => {
						console.log('-----上传失败-----'+JSON.stringify(res))
            this.$u.toast(JSON.parse(res.data).msg);
					}
			    })
			}
		}
	}
</script>

<style lang="scss" scoped>
    .top{
      width: 100%;
      background: #fff;
    }
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
    height: 100vh;
    overflow: hidden;
    background:#3c9cff linear-gradient(0deg, #116D9C 0%, #300E6A 100%);
	}

	.other-item {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    min-height: 130rpx;
    view{
      display: flex;align-items: center;
      border: 1rpx solid #2DDFFF;;
      background: rgba(45, 223, 255, 0.3);
      padding: 8rpx 20rpx;
      border-radius: 30rpx;
      margin-right: 30rpx;
      color:#fff;
      font-size: 32rpx;
    }
	}
  .center{
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 36rpx;
    .item-box{
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      //min-height: 100rpx;
      .item_title{
        height: 112rpx;
        width: 100%;
        image{
          width: 100%;
          height: 100%;
        }
      }
      .item-content{
        color:#fff;
      }
      .item-content:nth-child(1){
        width: 400rpx;
        height: 350rpx;
        margin-top: 40rpx;
        image{
          width:100%;
          height:100%;
        }
      }
      .item-content:nth-child(2){
        margin-top: 40rpx;
      }
      .item-content:nth-child(3){
        margin-top: 20rpx;
      }
    }
    .item-box:nth-child(1){
        //margin-top: 20rpx;
    }
    .item-box:nth-child(3){
      margin-top: 40rpx;
      .top_vicoe{
        color: #fff;
        background:rgba(45, 223, 255, 0.3);
        padding: 16rpx 64rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
      }
      .vioce-item{
        width:180rpx;
        height: 180rpx;
        margin-top: 30rpx;
        image{
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .modal-box{
    width: 488rpx;
    height: 456rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .close{
      position:absolute;
      width: 54rpx;
      height: 54rpx;
      top: -80rpx;
      right: -40rpx;
      image{
        width: 100%;
        height: 100%;
      }
    }
    .modal-title{
      font-size: 33rpx;
      color: #666666;
      margin-top: 38rpx;
    }
    .info_self{
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 60rpx;
      .self_img{
        width: 84rpx;
        height: 84rpx;
      }
      .phone{
        font-size: 26rpx;
        font-weight: bold;
        color: #333;
        margin-top: 24rpx;
      }
    }

    .call-btn{
      width: 342rpx;
      height: 72rpx;
      background: linear-gradient(180deg, #24BFD3, #2199D5);;
      box-shadow: 0rpx 2rpx 4rpx 0rpx rgba(220, 168, 109, 0.45);
      border-radius: 34rpx;
      font-size: 28rpx;
      font-weight: normal;
      color: #FFFFFF;
      text-align: center;
      line-height: 72rpx;
      margin-top: 60rpx;
    }
  }
/deep/ .u-safe-bottom{
  display: none;
}
</style>
